import { createStore } from 'vuex'
import axios from 'axios'
import { Increment } from './mutation.type'
import home from './modules/home'
import user from './modules/user'

export default createStore({
  state () {
    return {
      count: 0,
      age: 20,
      height: 1.88,
      name: 'jixiao',
      books: [
        { name: 'js高级', price: 20, count: 1 },
        { name: 'node高级', price: 30, count: 8 },
        { name: 'react高级', price: 50, count: 9 },
        { name: 'vue高级', price: 80, count: 10 }
      ],
      discount: 0.9,
      banner: [],
      banner1: [],
      rootCount: 0
    }
  },
  mutations: {
    add (state, payload) {
      state.count += payload
    },
    decrement (state, payload) {
      state.count -= payload
    },
    [Increment] (state, payload) {
      console.warn('payload', payload)
      state.count += payload.n
    },
    getBanner (state, payload) {
      console.warn('获取banner数据===', payload)
      state.banner = payload
      state.banner1 = payload
    }
  },
  actions: {
    addTWO ({ commit }, payload) {
    //   setTimeout(() => {
      commit('add', payload)
    //   }, 2000)
    },
    incrementAction1 ({ commit }, payload) {
      commit('decrement', payload)
    },
    incrementAction ({ dispatch }, payload) {
      console.warn('context==', dispatch, payload)
      dispatch('getBanner')
    },
    getBanner1 (context) {
      console.warn(2222)
    },
    getBanner (context) {
      console.warn('getBanner1111')
      return new Promise((resolve, reject) => {
        axios.get('./img.json').then(res => {
          console.log(res.data)
          context.commit('getBanner', res.data)
          resolve({ name: 'jixiao', age: 20 })
        }).catch(error => {
          console.log('error', error)
          reject(error)
        })
      })
    }
  },
  getters: {
    getterCount (state, getters) {
      let total = 0
      state.books.map(item => {
        total += item.count * item.price
      })
      return total * (getters.currentDisCount)
    },
    currentDisCount (state, getters) {
      return state.discount * (0.6)
    },
    // count 大于n的情况
    totalGreen (state, getters) {
      return function (n) {
        let count1 = 0
        state.books.map(item => {
          if (item.count > n) {
            count1 += item.count * item.price
          }
        })
        return count1 * (getters.currentDisCount)
      }
    },
    nameInfo (state, getters) {
      return 'name: ' + state.name
    },
    ageInfo (state, getters) {
      return 'age: ' + state.age
    },
    heightInfo (state, getters) {
      return 'height: ' + state.height
    }
  },
  modules: {
    home,
    user
  }
})
